package com.qiche.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qiche.aspect.Result;
import com.qiche.dto.SimpleMemberDto;
import com.qiche.dto.StoreMemberCarDto;
import com.qiche.dto.StoreMemberDto;
import com.qiche.enums.CustomerType;
import com.qiche.mapper.StoreMemberCarMapper;
import com.qiche.mapper.StoreMemberMapper;
import com.qiche.model.StoreMember;
import com.qiche.model.StoreMemberCar;
import com.qiche.model.User;
import com.qiche.param.StoreMemberParam;
import com.qiche.service.StoreMemberService;
import com.qiche.util.ExcelUtil;
import com.qiche.util.UserUtils;
import com.qiche.vo.StoreMemberVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author chendezhi
 * @date 2018/3/28 17:00
 */
@Service
public class StoreMemberServiceImpl extends BaseService<StoreMember> implements StoreMemberService {

    private Logger logger= LoggerFactory.getLogger(StoreMemberServiceImpl.class);
    @Autowired
    private StoreMemberMapper storeMemberMapper;
    @Autowired
    private StoreMemberCarMapper storeMemberCarMapper;
    @Autowired
    private ExcelUtil excelUtil;
    @Override
    public PageInfo<StoreMemberVo> selectStoreMemberWithCarsByPage(StoreMemberParam param, int page, int limit) {
        User currentUser= UserUtils.getCurrentUser();
        if (!UserUtils.checkIsAdmin(currentUser)) {
            param.setMerchantId(currentUser.getMerchantId().longValue());
        }
        PageHelper.startPage(page, limit);
        List<StoreMemberVo> storeMemberVoList = storeMemberMapper.selectStoreMemberWithCarsByPage(param);
        return new PageInfo<>(storeMemberVoList);
    }

    @Override
    public StoreMember selectByPhoneAndMerchantId(String phone,Integer merchantId) {
        Example example = new Example(StoreMember.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("phone", phone);
        criteria.andEqualTo("merchantId", merchantId);
        List<StoreMember> storeMemberList = selectByExample(example);
        if (!storeMemberList.isEmpty()) {
            return storeMemberList.get(0);
        }
        return null;
    }
    @Override
    public StoreMember selectByOpenidUnionidMerchantid(String openid, String unionId,Long merchantId) {
        Example example = new Example(StoreMember.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("unionid", unionId);
        criteria.andEqualTo("openid", openid);
        criteria.andEqualTo("merchantId", merchantId);
        List<StoreMember> storeMemberList = selectByExample(example);
        if (!storeMemberList.isEmpty()) {
            return storeMemberList.get(0);
        }
        return null;
    }

    @Override
    public StoreMember selectByOpenidMerchantid(String openid,Long merchantId) {
        Example example = new Example(StoreMember.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("openid", openid);
        criteria.andEqualTo("merchantId", merchantId);
        List<StoreMember> storeMemberList = selectByExample(example);
        if (!storeMemberList.isEmpty()) {
            return storeMemberList.get(0);
        }
        return null;
    }

    @Override
    public List<StoreMember> selectByMerchantId() {
        User currentUser = UserUtils.getCurrentUser();
        Example example = new Example(StoreMember.class);
        Example.Criteria criteria = example.createCriteria();
        if(!UserUtils.checkIsAdmin(currentUser)){
            criteria.andEqualTo("merchantId", currentUser.getMerchantId());
        }
        return selectByExample(example);
    }

    @Override
    public Result<StoreMemberVo> saveStoreMember(StoreMemberDto storeMemberDto) {
    	User currentUser = UserUtils.getCurrentUser();
        //会员列表 手机号码不能重复
        StoreMember storeMember=selectByPhoneAndMerchantId(storeMemberDto.getPhone(),currentUser.getMerchantId());
        if (storeMember != null)
            return Result.createByErrorMessage("手机号已经存在");

        StoreMember storeMemberToInsert = new StoreMember();
        storeMemberToInsert.setType(CustomerType.NORMAL);
        storeMemberToInsert.setName(storeMemberDto.getName());
        storeMemberToInsert.setPhone(storeMemberDto.getPhone());
        storeMemberToInsert.setConsumeCount(0);
        storeMemberToInsert.setConsumeMoney(new BigDecimal(0));
        storeMemberToInsert.setCreateTime(new Date());
        storeMemberToInsert.setMerchantId(UserUtils.getCurrentUser().getMerchantId().longValue());
        boolean insertOk = storeMemberMapper.insert(storeMemberToInsert) > 0 ? true : false;

        //关联插入车辆信息
        List<StoreMemberCarDto> storeMemberCars = storeMemberDto.getStoreMemberCars();
        for (StoreMemberCarDto storeMemberCarDto : storeMemberCars) {
            StoreMemberCar storeMemberCar=new StoreMemberCar();
            storeMemberCar.setFrameNumber(storeMemberCarDto.getFrameNumber());
            storeMemberCar.setCarInfo(storeMemberCarDto.getCarInfo());
            storeMemberCar.setPlateNumber(storeMemberCarDto.getPlateNumber());
            storeMemberCar.setStoreMemberId(storeMemberToInsert.getId());
            insertOk =   storeMemberCarMapper.insert(storeMemberCar) > 0 ? true : false && insertOk;
        }

        if (insertOk) {
            return Result.createBySuccessMessage("保存成功");
        }
        return Result.createByErrorMessage("保存失败");
    }

    @Override
    public Result delStoreMember(Long storeMemberId) {
        int deleteCount = storeMemberMapper.deleteByPrimaryKey(storeMemberId);
        //同时删除该会员的车辆关联信息
        Example example = new Example(StoreMemberCar.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storeMemberId", storeMemberId);

        int deleteCount2 = storeMemberCarMapper.deleteByExample(example);
        if (deleteCount > 0 && deleteCount2 > 0) {
            return Result.createBySuccessMessage("删除成功");
        }
        return Result.createByErrorMessage("删除失败");
    }

    @Override
    public Result analysisAndImport(String path) {
        List<String> importSuccess=new ArrayList<>();
        List<String> importFailure=new ArrayList<>();
        String currentPhone="";
        try {
            List<List<String>> result = excelUtil.readXls(path);
            for (List<String> list : result) {
                try {
                    String memberName = list.get(0);
                    String memberPhone = list.get(1);
                    String memberType =list.get(4);   //是否会员
                    currentPhone = memberPhone;

                    StoreMember storeMember=new StoreMember();
                    storeMember.setName(memberName);
                    storeMember.setPhone(memberPhone);
                    storeMember.setMerchantId( UserUtils.getCurrentUser().getMerchantId().longValue());
                    storeMember.setType(Integer.parseInt(memberType));
                    storeMemberMapper.insert(storeMember);

                    String plateNumber = list.get(2);
                    String carInfo = list.get(3);
                    StoreMemberCar car = new StoreMemberCar();
                    car.setStoreMemberId(storeMember.getId());
                    car.setPlateNumber(plateNumber);
                    car.setCarInfo(carInfo);
                    storeMemberCarMapper.insert(car);
                    importSuccess.add(currentPhone);
                }catch (Exception e){
                    e.printStackTrace();
                    importFailure.add(currentPhone);
                }
            }
            if (importFailure.size()==0){
                return Result.createBySuccessMessage("所有数据已经成功导入");
            }else {
                return Result.createBySuccessMessage("手机号码为"+importFailure.toString()+"的记录无法正确导入");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.createByErrorMessage("文件解析错误");
        }
    }

    @Override
    public Result downloadTemplate(HttpServletRequest request, HttpServletResponse response) {
        try {
            InputStream fis = StoreMemberServiceImpl.class.getResourceAsStream("/static/template.xlsx");
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            response.setContentType("application/vnd.ms-excel");
            String fileNames = "客户信息模板";
            String agent = request.getHeader("USER-AGENT");
            String codedfilename = "";
            if (null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident")) {// ie
                String name = java.net.URLEncoder.encode(fileNames, "UTF8");
                codedfilename = name;
            } else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等
                codedfilename = new String(fileNames.getBytes("UTF-8"), "iso-8859-1");
            }
            response.addHeader("Content-Disposition", "attachment; filename=\"" + codedfilename + ".xlsx" + "\"");
            response.getOutputStream().write(buffer);
            return Result.createBySuccessMessage("下载成功");
        } catch (IOException e) {
            e.printStackTrace();
            logger.debug("下载客户信息表-模板文件报错" + e.getMessage(), e);
            return Result.createByErrorMessage("下载出错");
        }
    }


    /**
     * 根据时间范围 统计门店客户数量
     * @param merchantId
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public int countByTimeRange(Integer merchantId, Date startTime, Date endTime) {
        Example example = new Example(StoreMember.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("merchantId", merchantId);
        if (startTime != null && endTime != null) {
            criteria.andGreaterThanOrEqualTo("createTime", startTime);
            criteria.andLessThanOrEqualTo("createTime", endTime);
        }
        return storeMemberMapper.selectCountByExample(example);
    }


    /**
     * 根据关键字(手机号码，姓名，车牌号码)检索客户
     * @param keyword
     * @param currentUser
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<SimpleMemberDto> searchByPhoneOrNameOrCarNum(String keyword, User currentUser, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SimpleMemberDto> simpleMemberDtos = storeMemberMapper.searchByPhoneOrNameOrCarNum(keyword, currentUser.getMerchantId());
        return new PageInfo<>(simpleMemberDtos);
    }




}
